/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.TimerTask;

/**
 *
 * @author John
 */
public class Job extends TimerTask {

    static String WORKHOME = "/mnt/datadisk4/CASP9/";

    public void run() {
        try {
            deal_job();
        } catch (Exception e) {
            System.out.println("错误信息：" + e.getMessage());
        }
    }

    public static void deal_job() throws Exception {
        //连接数据库
        String url = "jdbc:mysql://202.195.130.254:3306/Predict?user=root&password=111111";
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection conn = null;
        conn = DriverManager.getConnection(url);
        // Do something with the Connection
        Statement stmt = conn.createStatement();
        String sql = "SELECT RequestID,Seq,FastaCode,Email FROM PredictRequest where  Finished=0 order by RequestID desc";
        ResultSet rs = stmt.executeQuery(sql);
        while(rs.next()) {
            //获取记录信息
            String sRequestID = rs.getString("RequestID");
            String sFastaCode = rs.getString("FastaCode");
            String to = rs.getString("Email");
            String sSeq = rs.getString("Seq");
            //处理请求
            String sSQL;
            if (deal_request(sRequestID, sFastaCode, sSeq, to) == -1) {
                sSQL = "Update  PredictRequest set Finished=-1 where RequestID=" + sRequestID;
                System.out.println("released failed(" + sRequestID + ")");
            } else {
                //update release location
                String sWorkFold = sFastaCode + "_" + sRequestID;
                sSQL = "Update  PredictRequest set ReleaseLocation='" + WORKHOME + sWorkFold + "',Finished=1 where RequestID=" + sRequestID;
                System.out.println("released done(" + sRequestID + ")");
            }
            stmt.executeUpdate(sSQL);
            //处理完毕

            //新的查询
            sql = "SELECT RequestID,Seq,FastaCode,Email FROM PredictRequest where  Finished=0 order by RequestID desc";
            rs = stmt.executeQuery(sql);
        }
        //关闭连接
        rs.close();
        stmt.close();
        conn.close();

    }

    public static int deal_request(String sRequestID, String sFastaCode, String sSeq, String to) {
        int iReturn = 1;//1:success;-1:failed

        String sFileName = WORKHOME + "T" + sRequestID + ".fasta";


        try {
            String log = "";
            //output log file
            //if log file exists ,delete it
            File logfile = new File("./log/T" + sRequestID + "_log.txt");
            if (logfile.exists() && logfile.isFile()) {
                logfile.delete();
            }

            FileWriter fw = new FileWriter("./log/T" + sRequestID + "_log.txt");
            BufferedWriter bw = new BufferedWriter(fw);


            FileWriter fstream = new FileWriter(sFileName);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(sSeq);
            out.write('\n');
            out.close();
            System.out.println("fasta file is  created");


            //exeute make fragement
            Runtime rt = Runtime.getRuntime();
            System.out.println("run first.sh" + "T" + sRequestID);
            String[] cmd1 = {"/bin/sh", "-c", "./first.sh " + "T" + sRequestID};
            Process proc1 = rt.exec(cmd1);
            //获取输出流

            InputStream shin = proc1.getErrorStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(shin));
            while ((log = br.readLine()) != null) {
                bw.write(log);
                bw.newLine();
            }
            proc1.waitFor();
            bw.flush();
            bw.close();
            br.close();
            fw.close();
            shin.close();
            proc1.waitFor();
            System.out.println("first.sh finished T" + sRequestID);
            //发送附件
            if (iReturn == 1) {
                Mail.send(to, sFastaCode, WORKHOME + "T" + sRequestID);
            }
        } catch (Exception ex) {
            System.out.println("Exception: " + ex.getMessage());
            iReturn = -1;

        }
        return iReturn;
    }
}
